import router, { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index.vue'
import ParentView from '@/components/ParentView/index.vue'
import InnerLink from '@/layout/components/InnerLink/index.vue'
// import piniaPersistConfig from '@/config/piniaPersist'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

export const usePermissionStore = defineStore({
  id: 'permission',
  state: () => ({
    routes: [] as any[],
    addRoutes: [] as any[],
    defaultRoutes: [] as any[],
    sidebarRouters: [] as any[],
    activeMenu: '' as any,
    topbarRouters: [] as any[],
    activeRouters: [] as any[],
  }),
  actions: {
    setRoutes(routes: any[]) {
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
    },
    setDefaultRoutes(routes: any[]) {
      this.defaultRoutes = constantRoutes.concat(routes)
    },
    setSidebarRouters(routes: any[]) {
      this.sidebarRouters = routes
    },
    setActiveRouters(routes: any[]) {
      this.activeRouters = routes
    },
    setTopbarRouters(routes: any[]) {
      this.topbarRouters = routes
    },
    setActiveMenu(path:any) {
      this.activeMenu = path
    },
    clearSidebarRouters(){
      this.sidebarRouters = []
    },
    generateRoutes() {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const sdata = JSON.parse(JSON.stringify(res.data))
          const rdata = JSON.parse(JSON.stringify(res.data))
          const defaultData = JSON.parse(JSON.stringify(res.data))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          const defaultRoutes = filterAsyncRouter(defaultData)
          this.setRoutes(rewriteRoutes)
          // this.setSidebarRouters(sidebarRoutes)
          this.setActiveRouters(sidebarRoutes)
          // 如果需要和静态路由组合就显示
          // this.setTopbarRouters(constantRoutes.concat(sidebarRoutes))
          this.setTopbarRouters(defaultRoutes)
          resolve(rewriteRoutes)
        })
      })
    }
  }
})

// 遍历后台传来的路由字符串，转换为组件对象，并拼接子路由路径
function filterAsyncRouter(asyncRouterMap: any[], lastRouter:any = false, type:any = false) {

  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true;
  });
}

function filterChildren(childrenMap: any[], lastRouter: any = false) {
  const children: any[] = [];

  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach((c: any) => {
          c.path = `${el.path}/${c.path}`;
          if (c.children && c.children.length) {
            children.push(...filterChildren(c.children, c));
          } else {
            children.push(c);
          }
        });
      } else {
        if (lastRouter) {
          el.path = `${lastRouter.path}/${el.path}`;
        }
        if (el.children && el.children.length) {
          children.push(...filterChildren(el.children, el));
        } else {
          children.push(el);
        }
      }
    } else {
      if (lastRouter) {
        el.path = `${lastRouter.path}/${el.path}`;
      }
      children.push(el);
    }
  });

  return children;
}



// 动态加载视图组件
const loadView = (view:any) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
}
